package com.gglx.app.clip.components
{
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.NetStatusEvent;
	import flash.events.StageVideoAvailabilityEvent;
	import flash.geom.Rectangle;
	import flash.media.StageVideo;
	import flash.media.StageVideoAvailability;
	import flash.net.NetConnection;
	import flash.net.NetStream;

	public class StageVideoPlayer extends Sprite
	{
		private static var isOk:Boolean=true;
		public var STREAM_URL:String="...";
		private var netConnection:NetConnection;
		private var netStream:NetStream;
		private var video:StageVideo;
		private var addedToStage:Boolean;
		private var svEnabled:Boolean;

		public function StageVideoPlayer()
		{
			super();
			addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
		}

		private function onAddedToStage(e:Event):void
		{
			stage.addEventListener(StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY, onAvail);
			removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
		}

		protected function onAvail(event:StageVideoAvailabilityEvent):void
		{
			if (event.availability == StageVideoAvailability.AVAILABLE)
			{
				svEnabled=true;
			}

			connectStream();
		}

		private function connectStream():void
		{
			if (!svEnabled)
			{
				return;
			}

			netConnection=new NetConnection();
			netConnection.addEventListener(NetStatusEvent.NET_STATUS, onConnectionNetStatus);
			netConnection.connect(null);
		}

		private function onConnectionNetStatus(event:NetStatusEvent):void
		{
			if (event.info.code == "NetConnection.Connect.Success")
			{
				isOk=true;
					//startStream();
			}
		}

		public function startStream():void
		{
			if (isOk)
			{
				netStream=new NetStream(netConnection);
				netStream.client=this;
				video=stage.stageVideos[0];
				video.viewPort=new Rectangle(0, 0, stage.stageWidth, stage.stageHeight);
				video.attachNetStream(netStream);
				netStream.play(STREAM_URL);
			}
		}

		private function onMetaData():void
		{
		}
	}
}
